<template>
 <div class="validate-input-container pb-3">
     <input 
        type="email" 
        class="form-control"
        :class="{'is-invalid':inputRef.error}"
        id="exampleInputEmail0" 
        v-model="inputRef.val"
        @blur="validateInput"
        >
        <div class='invalid-feedback' v-if="inputRef.error">{{inputRef.message}}</div>
 </div>
</template>

<script lang='ts'>
import {defineComponent,PropType,reactive} from 'vue'

interface emailProps {
    type: 'required' | 'email',
    message: string
}
export type RuleProps = emailProps[]
export default defineComponent({
    props: {
        rules: Array as PropType<RuleProps>
    },
    setup(props) {
        const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
        const inputRef = reactive({
            val: '',
            error: false,
            message: ''
        })

        const validateInput = ()=> {
            if(props.rules) {
             
                const allPassed = props.rules.every(rule => {
                    let passed = true;
                    inputRef.message = rule.message
                    switch (rule.type) {
                        case 'required':
                           passed = inputRef.val.trim() != ''
                            break;

                        case 'email':
                            passed = emailReg.test(inputRef.val)
                            break;
                    
                        default:
                            break;
                    }
                    return passed
                })
                inputRef.error = !allPassed
            }
            return
        }
       
        return {
           inputRef,
           validateInput
        }
    }
})
</script>

<style>

</style>